package com.okbihuo.perm.component.sms.controller;

import com.okbihuo.perm.component.sms.logic.SmsLogic;
import com.okbihuo.perm.component.sms.logic.type.SmsModuleType;
import com.okbihuo.perm.component.sms.logic.type.SmsType;
import com.okbihuo.perm.core.tool.api.BaseException;
import com.okbihuo.perm.core.tool.api.R;
import com.okbihuo.perm.core.tool.api.ResultCode;
import com.okbihuo.perm.core.tool.utils.WebUtil;
import es.moki.ratelimitj.core.limiter.request.RequestLimitRule;
import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter;
import es.moki.ratelimitj.inmemory.InMemorySlidingWindowRequestRateLimiter;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 短息controller
 * @author stt
 */
@RestController
@RequestMapping("/open/qw/sms")
@RequiredArgsConstructor
public class SmsController {

    private final SmsLogic smsLogic;


    /**
     * 50 request per minute, per key
     */
    Set<RequestLimitRule> rules = Collections.singleton(RequestLimitRule.of(10, TimeUnit.SECONDS, 1));
    RequestRateLimiter requestRateLimiter = new InMemorySlidingWindowRequestRateLimiter(rules);

    /**
     * 50 request per minute, per key
     */
    Set<RequestLimitRule> rules2 = Collections.singleton(RequestLimitRule.of(1, TimeUnit.DAYS, 50));
    RequestRateLimiter requestRateLimiter2 = new InMemorySlidingWindowRequestRateLimiter(rules2);

    /**
     *注册短信
     * @param phone
     * @param request
     * @return
     */
    @GetMapping("sendRegisterSms")
    public R<Object> sendRegisterSms(@RequestParam("phone")String phone, HttpServletRequest request) throws BaseException {
        String ipAddress = WebUtil.getIP(request);
        if(requestRateLimiter.overLimitWhenIncremented(ipAddress)){
            throw new BaseException(ResultCode.OVER_LIMIT);
        }
        return R.data(smsLogic.sendSMS(phone, SmsModuleType.SMS_REGISTER,ipAddress , SmsType.REGISTER));
    }

    /**
     * 忘记密码短信
     * @param phone
     * @param request
     * @return
     */
    @GetMapping("sendResetPwdSms")
    public R<Object> sendForgetPwdSms(@RequestParam("phone")String phone, HttpServletRequest request) throws BaseException {
        String ipAddress = WebUtil.getIP(request);
        if(requestRateLimiter2.overLimitWhenIncremented(phone)){
            throw  new BaseException(ResultCode.OVER_LIMIT,"今日密码找回次数已用完!");
        }
        return R.data(smsLogic.sendSMS(phone, SmsModuleType.SMS_FORGET_PASSWORD,ipAddress , SmsType.RESET_PASSWORD));
    }


}
